package pt.fct.mpc.lastfm.artist;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import pt.fct.mpc.lastfm.R;
import pt.fct.mpc.lastfm.connectivity.LastfmBluetoothUnavailableException;
import pt.fct.mpc.lastfm.connectivity.LastfmURL;
import pt.fct.mpc.lastfm.event.EventData;
import pt.fct.mpc.lastfm.event.EventsXmlHandler;
import pt.fct.mpc.lastfm.geo.LastfmGeoEventsActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class ArtistEventsActivity extends Activity {

	private static final String TAG = "Last.fm Artist Activity";
	private boolean gotEvents = false;
	ArtistData artistDataSet = null;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);

		// Reads the info sent by the intent
		Intent the_intent_that_gave_life_to_everything = getIntent();
		Bundle intent_data = the_intent_that_gave_life_to_everything
				.getExtras();

		if (intent_data == null) {
			Log.e(TAG, "No extra data");
			finish();
		}

		artistDataSet = (ArtistData) intent_data
				.getSerializable("artistserial");

		if (artistDataSet == null) {
			Log.e(TAG, "Null values from bundle: albumDataSet = "
					+ artistDataSet);
			finish();
		}

		if (!gotEvents)
			getEvents();
		createEventsTab();
	}

	private void createEventsTab() {
		ArrayAdapter<String> eventsArrayAdapter = new ArrayAdapter<String>(
				this, R.layout.list_item);
		ListView resultsListView = (ListView) findViewById(R.id.ListView);
		resultsListView.setAdapter(eventsArrayAdapter);

		List<EventData> events = artistDataSet.getEvents();
		for (int i = 0; i < events.size(); i++)
			eventsArrayAdapter.add(events.get(i).getTitle() + "\n"
					+ events.get(i).getVenue_name() + "\n"
					+ events.get(i).getCity() + " - "
					+ events.get(i).getCountry() + "\n"
					+ events.get(i).getDate());

		resultsListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				List<EventData> event_list = artistDataSet.getEvents();
				if (event_list == null) {
					Log.e(TAG, "Null event list for artist");
					return;
				}

				EventData event = event_list.get(position);
				if (event == null) {
					Log.e(TAG, "Null event in position " + position);
					return;
				}

				String date = event.getDate();
				String lat = event.getGeo_lat();
				String lng = event.getGeo_long();
				String title = event.getTitle();
				String artist = artistDataSet.getName();

				Bundle intent_data = new Bundle();
				intent_data.putString("artist", artist);
				intent_data.putString("title", title);
				intent_data.putString("date", date);
				intent_data.putString("latitude", lat);
				intent_data.putString("longitude", lng);

				Intent intent = new Intent(getApplicationContext(),
						LastfmGeoEventsActivity.class);
				intent.putExtras(intent_data);
				startActivity(intent);
			}
		});
	}

	private void getEvents() {
		String artist_name = artistDataSet.getName();
		try {
			artist_name = URLEncoder.encode(artistDataSet.getName(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new RuntimeException("encoding problems");
		}

		String request_params = "?method=artist.getevents" + "&artist="
				+ artist_name + "&api_key="
				+ getString(R.string.lastfm_api_key);

		String request_str = getString(R.string.lastfm_api_url)
				+ request_params;

		LastfmURL request_url = null;
		try {
			request_url = new LastfmURL(request_str);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = null;
		try {
			sp = spf.newSAXParser();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}

		XMLReader xr = null;
		try {
			xr = sp.getXMLReader();
		} catch (SAXException e) {
			e.printStackTrace();
		}

		EventsXmlHandler myEventsXmlHandler = new EventsXmlHandler();
		xr.setContentHandler(myEventsXmlHandler);

		try {
			xr.parse(new InputSource(request_url.openStream()));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (LastfmBluetoothUnavailableException e) {
			e.printStackTrace();
		}

		request_url.finished();
		artistDataSet.setEvents(myEventsXmlHandler.getParsedData());

		this.gotEvents = true;
	}
}